package com.sise.netty2.netty_client_server;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;

/**
 * netty客户端代码
 *
 * @Author idea
 * @Date created in 9:25 下午 2020/4/19
 */
public class NettyClient {

    private void clientStart() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        System.out.println("channel init ....");
                        socketChannel.pipeline().addLast(new ClientHandler());
                    }
                });
        System.out.println("start to connect .... ");
        try {
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",8888).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient();
        System.out.println("====== client is start =====");
        nettyClient.clientStart();
    }

    class  ClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            try{
                ByteBuf byteBuf = (ByteBuf) msg;
                System.out.println(byteBuf.toString());
            }finally {
                ReferenceCountUtil.release(msg);
            }
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel is active...");

            final ChannelFuture channelFuture = ctx.writeAndFlush(Unpooled.copiedBuffer("HelloNetty".getBytes()));
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("send is end ...");
                }
            });


        }
    }
}
